package com.itheima.tanhua.interceptor;

import com.itheima.tanhua.entity.Admin;
import com.itheima.tanhua.utils.AppJwtUtil;
import com.itheima.tanhua.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头信息
        String token = request.getHeader("Authorization");
        if(!StringUtils.isEmpty(token)){
            token = token.replace("Bearer ", "");
        }
        //2.token校验
        Claims claims = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claims);
        //判断是否有效
        if (i == 1 || i == 2) {
            response.setStatus(401);
            return false;
        }
        //3.获取登录者id,手机号
        assert claims != null;
        Long id = claims.get("id", Long.class);
        String username = claims.get("username", String.class);
        Admin admin = new Admin();
        admin.setId(id);
        admin.setUsername(username);
        //4、将登陆者id存储到本地线程
        ThreadLocalUtil.set(admin);
        return true;
    }
}